package com.crois.barrier.admin.controller;


import com.crois.barrier.admin.entity.BarrierServer;
import com.crois.barrier.admin.resp.BarrierResponseWrapper;
import com.crois.barrier.admin.server.ServerListManager;
import com.crois.barrier.common.response.BarrierResponseEntity;
import com.crois.barrier.common.utils.UtilsAndCommons;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 15:41 2021/10/27
 */
@RestController
@RequestMapping(UtilsAndCommons.DEFAULT_BARRIER_ADMIN_HEALTH_BEAT_CHECK_CONTEXT)
public class ServerClusterController {
    private Logger LOGGER = LoggerFactory.getLogger(ServerClusterController.class);

    @Autowired
    private ServerListManager serverListManager;


    /***
     * barrier server heartbeat
     */
    @GetMapping(UtilsAndCommons.BARRIER_HEARTBEAT_CONTEXT)
    public BarrierResponseEntity<Void> serverClusterHeartbeat(BarrierServer server){

        LOGGER.debug("【server heart beat】，time:{},server:{},接收 服务端心跳成功！",new Date(),server);

        if (Objects.isNull(serverListManager.getServer(server.getAddressKey()))){
            serverListManager.putServer(server.getAddressKey(),server);
        }else {
            serverListManager.updateServer(server.getAddressKey(),server);
        }
        return BarrierResponseWrapper.ok();
    }


    /***
     * barrier server list
     */
    @GetMapping(UtilsAndCommons.BARRIER_LIST_CONTEXT)
    public BarrierResponseEntity<List<?>> serverClusterList() {
        return BarrierResponseWrapper.okList(serverListManager.getServerList());
    }

}
